package com.example.demo8;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.example.demo8.broadcastreceiver.MyReceiver;

public class MainActivity extends AppCompatActivity {
    private MyReceiver myReceiver;
    private LocalReceiver localReceiver;
    private LocalBroadcastManager localBroadcastManager;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //获取本地广播管理器实例
        localBroadcastManager = LocalBroadcastManager.getInstance(this);
        Button send1=findViewById(R.id.send_button1);
        Button send2=findViewById(R.id.send_button2);
        //发送标准广播,自己接收
        send1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //过滤意图
                Intent intent=new Intent("com.example.demo8.XIAOXI");
                //传入数据
                intent.putExtra("1024","有内鬼,停止交易");
                //发送系统全局广播
                sendBroadcast(intent);
                //发送本地广播
                localBroadcastManager.sendBroadcast(intent);

            }
        });
        //发送有序广播给demo9
        send2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //过滤意图
                Intent intent=new Intent("com.example.demo8.XINGE");
                //传入数据
                intent.putExtra("1234","黑吃黑???");
                //发送广播
                sendOrderedBroadcast(intent,null);
            }
        });
        //注册广播接收器
        IntentFilter intentFilter=new IntentFilter();
        intentFilter.addAction("com.example.demo8.XIAOXI");
        myReceiver = new MyReceiver();
        registerReceiver(myReceiver,intentFilter);
        localReceiver=new LocalReceiver();
        localBroadcastManager.registerReceiver(localReceiver,intentFilter);

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(myReceiver);
    }

    /**
     *
     */
    private class LocalReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            Toast.makeText(context,"本地广播管理已开启",Toast.LENGTH_SHORT).show();
        }
    }
}
